import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';
import 'package:zootix/models/zt_im_conversation.model.dart';
import 'package:zootix/models/zt_user_info.model.dart';
import 'package:zootix/screens/follow_conversation/zt_conversation_item.controller.dart';
import 'package:zootix/screens/follow_conversation/zt_conversations.controller.dart';
import 'package:zootix/store/zt_im_chat.store.dart';
import 'package:zootix/util/zt_common.util.dart';
import 'package:zootix/util/zt_screen_adaper_util.dart';
import 'package:zootix/widgets/zt_fade_in_cache_image.dart';
import 'package:zootix/constants/zt_router.dart';
import 'package:zootix/apis/zt-api.dart' as Api;

class ZtConversationItem extends StatefulWidget {
  late ZtImConversationModel conversationModel;
  // late final _itemController;
  late int index;

  ZtConversationItem(
      {super.key, required this.conversationModel, required this.index}) {
    // Get.put<ZtConversationItemController>(
    //     _itemController =
    //         ZtConversationItemController(conversationModel.userId!),
    //     permanent: false,
    //     tag: '${Random().nextInt(1000)}');
    // _itemController.userId = conversationModel.userId!;
  }

  @override
  State<ZtConversationItem> createState() => _ZtConversationItemState();
}

class _ZtConversationItemState extends State<ZtConversationItem> {
  final _controller = Get.find<ZtConversationController>();

  bool isCustomerService = false;
  ZtUserInfoModel? userInfo;
  @override
  void initState() {
    getUserInfo();
    super.initState();
  }

  getUserInfo() async {
    final response = await Api.getUserInfo(widget.conversationModel.userId!);
    if (response.data != null) {
      if (mounted) {
        setState(() {
          userInfo = ZtUserInfoModel.fromJson(response.data['data']);
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
        Get.toNamed(ZtRouteConfig.privateChat, arguments: {
          'nickname': userInfo?.nickname ?? widget.conversationModel.nickname,
          'userId': widget.conversationModel.userId,
          'avatar':
              userInfo?.avatarThumbUrl ?? widget.conversationModel.avatarUrl
        })!
            .then((value) async {
          final result = await ZtImChartStore.to.getConversations();
          ZtImChartStore.to.conversationList.assignAll(result);
        });
      },
      child: Slidable(
          key: const ValueKey(0),
          endActionPane: ActionPane(motion: const DrawerMotion(), children: [
            SlidableAction(
              onPressed: (BuildContext _) {
                ZtImChartStore.to.removeConversation(
                    widget.conversationModel.userId!,
                    widget.conversationModel.conversationType!);
              },
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
              icon: Icons.delete_outline,
              label: 'Delete',
            ),
          ]),
          child: Container(
            padding: EdgeInsets.symmetric(
                vertical: ZtScreenAdaper.height(20),
                horizontal: ZtScreenAdaper.width(20)),
            child: Row(children: [
              Stack(
                children: [
                  isCustomerService
                      ? Container(
                          height: ZtScreenAdaper.height(50),
                          width: ZtScreenAdaper.width(50),
                          clipBehavior: Clip.hardEdge,
                          padding: EdgeInsets.all(ZtScreenAdaper.width(5)),
                          decoration: BoxDecoration(
                              shape: BoxShape.circle, color: Colors.grey[400]),
                          child: Image(
                              width: ZtScreenAdaper.width(50),
                              image: const AssetImage(
                                  'assets/images/customer_servicer.png')))
                      : Container(
                          clipBehavior: Clip.hardEdge,
                          decoration: BoxDecoration(shape: BoxShape.circle),
                          width: ZtScreenAdaper.width(50),
                          child: ZtFadeInCacheImage(
                            width: ZtScreenAdaper.width(50),
                            url: userInfo?.avatarThumbUrl ?? '',
                          )),
                  if (widget.conversationModel.unreadCount! > 0)
                    Positioned(
                        right: 0,
                        top: 0,
                        child: Container(
                          width: ZtScreenAdaper.width(20),
                          height: ZtScreenAdaper.width(20),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              borderRadius:
                                  BorderRadius.circular(ZtScreenAdaper.sp(10)),
                              color: const Color(0xFFFF0000)),
                          child: Text(
                            '${(widget.conversationModel.unreadCount ?? 0) > 99 ? '99+' : widget.conversationModel.unreadCount}',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                fontSize: ZtScreenAdaper.sp(
                                    (widget.conversationModel.unreadCount ??
                                                0) >
                                            99
                                        ? 10
                                        : 14),
                                color: Colors.white,
                                fontWeight: FontWeight.w500),
                          ),
                        ))
                ],
              ),
              SizedBox(
                width: ZtScreenAdaper.width(15),
              ),
              Expanded(
                  child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    userInfo?.nickname ?? '',
                    maxLines: 2,
                    style: TextStyle(
                        overflow: TextOverflow.ellipsis,
                        fontSize: ZtScreenAdaper.sp(16),
                        fontWeight: FontWeight.w500),
                  ),
                  SizedBox(
                    height: ZtScreenAdaper.height(5),
                  ),
                  Text(
                    widget.conversationModel.lastMessageType !=
                            RCIMIWMessageType.text
                        ? '[${ZtCommonUtil.firstUppercase(widget.conversationModel.lastMessageType.toString().split('.')[1])}]'
                        : widget.conversationModel.lastMessage ?? '',
                    maxLines: 2,
                    style: TextStyle(
                      color: Colors.grey[500],
                      overflow: TextOverflow.ellipsis,
                      fontSize: ZtScreenAdaper.sp(14),
                    ),
                  ),
                ],
              )),
              SizedBox(
                width: ZtScreenAdaper.width(10),
              ),
              Column(
                children: [
                  Text(
                    _controller.formatConverstaionDate(
                        widget.conversationModel.operationTime!),
                    style: TextStyle(
                        color: const Color(0xFF000000).withOpacity(0.3),
                        fontSize: ZtScreenAdaper.sp(12)),
                  ),
                ],
              )
            ]),
          )),
    );
  }
}
